package com.nexgo.payment.trans.setting.terminalkey.downkey;

import android.support.annotation.NonNull;

import com.nexgo.oaf.apiv3.SdkResult;
import com.nexgo.oaf.apiv3.device.pinpad.AlgorithmModeEnum;
import com.nexgo.oaf.apiv3.device.pinpad.PinPad;
import com.nexgo.payment.App;
import com.nexgo.payment.R;
import com.nexgo.payment.aop.annotation.RunOnMainThread;
import com.nexgo.payment.api.ApiDeviceEngine;
import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.databases.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * 母POS导密钥相关接口
 *
 * @author 谭忠扬-YuriTam
 * @time 2017年08月30日
 */
public class DownloadKeyPresenter implements DownloadKeyContract.Presenter {
    private Logger mLog = LoggerFactory.getLogger(DownloadKeyPresenter.class.getSimpleName());

    private final DownloadKeyContract.View mView;
    private final DataSource mRepository;
    private PinPad mPinPad;
    private boolean isFirstTimes = true;

    public DownloadKeyPresenter(@NonNull DownloadKeyContract.View view, @NonNull DataSource repository) {
        mView = checkNotNull(view);
        mRepository = checkNotNull(repository);
        mView.setPresenter(this);
        mPinPad = ApiDeviceEngine.getInstance().getPinPad();
        if ("2".equals(mRepository.getParamValue(PreferencesConstants.MASTER_KEY_ALGORITHM))) {
            mPinPad.setAlgorithmMode(AlgorithmModeEnum.SM4);
        }
    }

    @Override
    public void start() {
        if (isFirstTimes) {
            onStartImportKey();
            isFirstTimes = false;
        }
    }

    @Override
    public void pause() {

    }

    @Override
    public void destroy() {
        if (mPinPad != null){
            mPinPad.cancelLoadKey();
        }
    }

    @Override
    public void onStartImportKey() {
        mLog.debug("启动子线程中灌装主密钥");
        postMainThread(() -> mView.showDownCount(SysConstant.TIME_OUT_60));
        //子线程中执行密钥灌输
        App.sExecutor.execute(() -> {
            //目前只支持串口号为：0
            mLog.debug("---------- 开始灌装主密钥 -----------");
            int retCode = mPinPad.loadKeyByCom(0, SysConstant.TIME_OUT_60);
            mLog.debug("灌装主密钥返回结果：{}", retCode);
            switch (retCode) {
                case SdkResult.Success:
                    postMainThread(() -> mView.showResult(App.sContext.getString(R.string.import_key_success)));
                    break;
                default:
                    postMainThread(() -> mView.showResult(App.sContext.getString(R.string.import_key_fail)));
                    break;
            }
            mLog.debug("---------- 结束灌装主密钥 -----------");
        });
    }

    @RunOnMainThread
    private void postMainThread(Runnable runnable) {
        runnable.run();
    }
}
